package com.solocredit.finance.data.dev.utils

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.ImageFormat
import android.graphics.Point
import android.hardware.Sensor
import android.hardware.SensorManager
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CameraManager
import android.os.Build
import android.view.WindowManager
import org.json.JSONArray
import org.json.JSONObject
import java.io.BufferedReader
import java.io.File
import java.io.InputStreamReader
import kotlin.math.pow
import kotlin.math.sqrt

object FlexiMolaHdwUtil {

    fun sorList(context: Context): String {
        val jsonArray = JSONArray()
        try {
            val sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
            val sensors = sensorManager.getSensorList(Sensor.TYPE_ALL)
            for (sensor in sensors) {
                val jsonObject = JSONObject().apply {
                    put("type", sensor.type.toString())
                    put("name", sensor.name.safe())
                    put("version", sensor.version.toString())
                    put("maxRange", sensor.maximumRange.toString().safe())
                    put("vendor", sensor.vendor.safe())
                    put("minDelay", sensor.minDelay.toString().safe())
                    put("power", sensor.power.toString().safe())
                    put("resolution", sensor.resolution.toString().safe())
                }
                jsonArray.put(jsonObject)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return jsonArray.toString()
    }

    private fun chrotmo(): Boolean {
        val buildTags = Build.TAGS
        return buildTags != null && buildTags.contains("test-keys")
    }

    private fun chrotmonext(): Boolean {
        val paths = arrayOf(
            "/system/app/Superuser.apk",
            "/sbin/su",
            "/system/bin/su",
            "/system/xbin/su",
            "/data/local/xbin/su",
            "/data/local/bin/su",
            "/system/sd/xbin/su",
            "/system/bin/failsafe/su",
            "/data/local/su"
        )
        return paths.any { File(it).exists() }
    }

    private fun chrotmolast(): Boolean {
        var process: Process? = null
        return try {
            process = Runtime.getRuntime().exec(arrayOf("/system/xbin/which", "su"))
            val reader = BufferedReader(InputStreamReader(process.inputStream))
            reader.readLine() != null
        } catch (t: Throwable) {
            false
        } finally {
            process?.destroy()
        }
    }

    private fun isDrot(): Boolean {
        return chrotmo() || chrotmonext() || chrotmolast()
    }

    fun chrot(): String {
        return if (isDrot()) "YES" else "NO"
    }


    fun kbard(context: Context): String {
        return try {
            val config = context.resources.configuration
            config.keyboard.toString().safe()
        } catch (e: Exception) {
            e.printStackTrace()
            ""
        }
    }

    fun isVirso(): String {
        val isMatch = (
                Build.BRAND.startsWith("generic") ||
                        Build.FINGERPRINT.startsWith("generic") ||
                        Build.FINGERPRINT.startsWith("unknown") ||
                        Build.HARDWARE.contains("goldfish") ||
                        Build.HARDWARE.contains("ranchu") ||
                        Build.MODEL.contains("google_sdk") ||
                        Build.MODEL.contains("Emulator") ||
                        Build.MODEL.contains("Android SDK built for x86") ||
                        Build.MANUFACTURER.contains("Genymotion") ||
                        (Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic")) ||
                        "google_sdk" == Build.PRODUCT)

        return if (isMatch) "YES" else "NO"
    }


    @SuppressLint("MissingPermission")
    fun gmdb(context: Context): String {
        return ""
    }

    fun gfsiz(context: Context): String {
        val cameraId = hfcm(context)
        return cmpix(context, cameraId)
    }

    fun bgsiz(context: Context): String {
        val cameraId = hbcm(context)
        return cmpix(context, cameraId)
    }

    private fun hfcm(context: Context): Int {
        var cid = -1
        val cameraManager = context.getSystemService(Context.CAMERA_SERVICE) as CameraManager
        try {
            val cameraIds = cameraManager.cameraIdList
            for (cID in cameraIds) {
                if (cID == CameraCharacteristics.LENS_FACING_BACK.toString()) {
                    cid = cID.toInt()
                    break
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return cid
    }

    private fun hbcm(context: Context): Int {
        var cid = -1
        try {
            val cameraManager = context.getSystemService(Context.CAMERA_SERVICE) as CameraManager
            val cameraIds = cameraManager.cameraIdList
            for (cID in cameraIds) {
                if (cID == CameraCharacteristics.LENS_FACING_FRONT.toString()) {
                    cid = cID.toInt()
                    break
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return cid
    }

    private fun cmpix(context: Context, paramInt: Int): String {
        var pixelValue = "0"
        if (paramInt == -1)
            return pixelValue

        try {
            val cameraManager = context.getSystemService(Context.CAMERA_SERVICE) as CameraManager
            val cameraCharacteristics = cameraManager.getCameraCharacteristics(paramInt.toString())
            val streamConfigurationMap =
                cameraCharacteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)
            val sizes = streamConfigurationMap?.getOutputSizes(ImageFormat.JPEG)
            if (!sizes.isNullOrEmpty()) {
                val fistSize = sizes[0]
                val gWidth = fistSize.width
                val gHeight = fistSize.height
                val pixels = (gWidth * gHeight / 10000)
                pixelValue = pixels.toString()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return pixelValue
    }

    fun pysiz(context: Context): String {
        var sizeStr = ""
        try {
            val point = Point()
            val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
            wm.defaultDisplay.getRealSize(point)
            val dm = context.resources.displayMetrics
            val x = (point.x / dm.xdpi.toDouble()).pow(2.0)
            val y = (point.y / dm.ydpi.toDouble()).pow(2.0)
            val screenInches = sqrt(x + y)
            sizeStr = screenInches.toString()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return sizeStr
    }
}
